#include <windowsx.h>
#include "Core/Log/LogManager.h"
#include "Core/File/File.h"
#include "WindowApp_Win32.h"


WindowApp * WindowApp::ms_pInstance = NULL;

WindowApp::WindowApp()
:m_uWidth(800), m_uHeight(600), m_bFullscreen(false)
{
}
	
WindowApp::~WindowApp()
{
}
	
error WindowApp::Create(HINSTANCE _hInstance, int _nCmdShow, const String & _strTitle)
{
	if( ms_pInstance )
	{
		LOG_ERROR("Error : Instance already created");
		return errFailed;
	}

	ms_pInstance = this;

	// Register the class
	WNDCLASSEX wcex;
	wcex.cbSize			= sizeof(WNDCLASSEX); 
	wcex.style          = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc    = WndProc;
	wcex.cbClsExtra     = 0;
	wcex.cbWndExtra     = 0;
	wcex.hInstance      = _hInstance;
	wcex.hIcon          = LoadIcon(NULL, IDI_APPLICATION);
	wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground  = NULL;
	wcex.lpszMenuName   = NULL;
	wcex.lpszClassName  = "Window Application";
	wcex.hIconSm        = NULL;
	if( !RegisterClassEx(&wcex) )
		return errFailed;

	// Create window
	RECT rc = { 0, 0, m_uWidth, m_uHeight };
	AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
	m_hWnd = CreateWindow( "Window Application", _strTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInstance, NULL);
	if( !m_hWnd )
		return errFailed;

	ShowWindow( m_hWnd, _nCmdShow ); // genere un evenement WM_SIZE
	UpdateWindow( m_hWnd );

	return errOK;
}

error WindowApp::Destroy()
{

	return errOK;
}

void WindowApp::Loop()
{
	MSG msg = {0};
	while( WM_QUIT != msg.message )
	{
		if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
		{
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		else
		{
			 // do the stuff
		}
	}
}

LRESULT CALLBACK WindowApp::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	int xPos = 0;
	int yPos = 0;
	int uSizeX = 0;
	int uSizeY = 0;
	unsigned int key  = 0;
	switch(msg) 
	{
	case WM_DESTROY:
		PostQuitMessage(0);
		break;

	case WM_MOUSEMOVE:
		break;

	case WM_SIZE:
		uSizeX = GET_X_LPARAM(lParam);
		uSizeY = GET_Y_LPARAM(lParam);
		LOG_INFO("Resize : %d x %d", uSizeX , uSizeY);
		break;

	default:
		return DefWindowProc(hWnd, msg, wParam, lParam);
	}

	return 0;
}
